package cn.microven.mindmap.oprations;

import cn.microven.mindmap.components.part.MapPart;
import cn.microven.mindmap.components.line.MapLine;
import cn.microven.mindmap.components.part.Part;
import cn.microven.mindmap.struture.MindMap;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.util.Pair;

import java.util.List;

public class AddLeafOperation implements Operation {

    private boolean isUserOperation = true;
    private List<Pair<MapLine, Part>> list;
    private VBox vBox;

    private Part root;

    private Pair<MapLine, Part> leaf;

    private Pane linesBox;

    /**
     * 构造方法
     *
     * @param vBox 子节点加入的 vBox
     * @param list 子节点列表
     * @param leaf 线与子节点组成的键值对
     * @param linesBox 线加入的布局
     *
     */
    public AddLeafOperation(Part root, List<Pair<MapLine, Part>> list, VBox vBox, Pane linesBox, Pair<MapLine, Part> leaf) {
        this.root = root;
        this.vBox = vBox;
        this.leaf = leaf;
        this.list = list;
        this.linesBox = linesBox;
    }

    public AddLeafOperation(boolean isUserOperation,Part root, List<Pair<MapLine, Part>> list, VBox vBox, Pane linesBox, Pair<MapLine, Part> leaf) {
        this(root,list,vBox,linesBox,leaf);
        this.isUserOperation = isUserOperation;
    }

    @Override
    public void start() {
        start(false);
    }

    public void start(boolean isRedo) {

        Part node = leaf.getValue();

        //添加节点
        vBox.getChildren().add((MapPart)node);
        //添加连线
        linesBox.getChildren().add(leaf.getKey());
        //设置Level
        leaf.getValue().setLevel(root.getLevel()+1);
        node.getRoot().setLevel(root.getLevel()+1);
        //更新TreeView图标
        node.getTreeItem().setIcon();
        //添加进列表
        list.add(leaf);
        //设置其父节点
        leaf.getValue().setParentPart(root);

        root.getTreeItem().getChildren().add(leaf.getValue().getTreeItem());

        if (isUserOperation && !isRedo)
            MindMap.addOperation(this);
    }

    @Override
    public void undo() {
        RemoveLeafOperation rlo = new RemoveLeafOperation(root,list,vBox,linesBox,leaf);
        rlo.start(true);
    }
}
